const useApiRes = require('../common/apiRes')
const asyncHandler = require("express-async-handler");
const { fetchAll, fetchOne } = require('../../tools/db/query');


// 获取打印日志列表
exports.list = asyncHandler(async (req, res, next) => {
    const params = req.body;
    const listSql = getListSql(params, false);
    const result = await fetchAll(listSql.sql, listSql.sqlParams);
    const totalSql = getListSql(params, true);
    const total = await fetchOne(totalSql.sql, totalSql.sqlParams);
    return useApiRes.success(res, {
        list: result,
        total: total.total,
        currentPage: params.page,
    });
})

function getListSql(params, isTotal = false) {
    let sql = "SELECT id,printerName,status,createTime,templateName FROM print_logs where 1=1 ";
    let sqlParams = [];
    if (params.printerName) {
        sql += ' AND printerName = ?';
        sqlParams.push(params.printerName);
    }
    if (params.status) {
        sql += ' AND status = ?';
        sqlParams.push(params.status);
    }
   
    if (isTotal) {
        sql = 'SELECT COUNT(*) as total FROM (' + sql + ') as t';
    } else {
        sql += ' ORDER BY id DESC LIMIT ?, ?';
        sqlParams.push((params.page - 1) * params.pageSize, params.pageSize);
    }
    return { sql, sqlParams };
}

